﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZedGraph;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Text.RegularExpressions;

namespace CalcSharp.Core.Containers
{
    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    class Diagram
    {
        public string desc;
        public PointPairList value;
    }

    class DiagrammManager: IMemMan<Diagram, PointPairList>
    {
        private Dictionary<string, PointPairList> Engine;

        public DiagrammManager()
        {
            this.Engine = new Dictionary<string, PointPairList>();
        }

        public int Count
        {
            get { return Engine.Count; }
        }

        public void Clear()
        {
            Engine.Clear();
        }

        public bool isset(string name)
        {
            return Engine.ContainsKey(name);
        }

        public void unset(string name)
        {
            Engine.Remove(name);
        }

        public int Add(Diagram item)
        {
            if (Engine.ContainsKey(item.desc)) Engine[item.desc] = item.value;
            else Engine.Add(item.desc, item.value);
            return Engine.Count;
        }

        public Diagram PackSingle(string name)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentException("Name can't be null");
            name = name.ToLower();
            Diagram ret = new Diagram();
            ret.value = Engine[name];
            ret.desc = name;
            return ret;
        }

        public string[] keys
        {
            get { return Engine.Keys.ToArray(); }
        }

        public PointPairList this[string name]
        {
            get
            {
                name = name.ToLower(CultureInfo.CurrentCulture);
                string test = Regex.Replace(name, @"^\$[a-z1-9_-]+", "-ok-");
                if (test != "-ok-") throw new CSException("Incorrect variable name!");
                PointPairList val = null;
                if (this.Engine.ContainsKey(name)) val = Engine[name];
                return val;
            }
            set
            {
                name = name.ToLower(CultureInfo.CurrentCulture);
                string test = Regex.Replace(name, @"^\$[a-z1-9_-]+", "-ok-");
                if (test != "-ok-") throw new CSException("Incorrect variable name: " + name);
                if (MiscCoreFuncts.protectedconstant(name)) throw new CSException("This is a protected constant! Choose another name!");
                if (this.Engine.ContainsKey(name)) this.Engine[name] = value;
                else
                {
                    this.Engine.Add(name, value);
                }
            }
        }
    }
}
